<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { useBooleanStore } from '@/store';
  import { Notification } from '@arco-design/web-vue';
  import { addPerson } from '@/api/system-basic';

  const form = ref({
    deliveryEmpCode: '',
    deliveryEmpName: '',
  });
  const showDrawer = ref<boolean>(false);
  const booleanStore = useBooleanStore();

  // 监听弹框
  watch(
    () => booleanStore.boolValue,
    (newValue: boolean) => {
      if (booleanStore.num === 15) showDrawer.value = newValue;
      form.value.deliveryEmpCode = '';
      form.value.deliveryEmpName = '';
    }
  );

  function afterVisibleChange(val: any) {
    if (!val) {
      booleanStore.toggleBool(15);
    }
  }
  function handleCancel() {
    booleanStore.toggleBool(15);
  }
  const formRef = ref<any>('');

  const rules = {
    deliveryEmpCode: [
      { required: true, message: '不能为空' },
      {
        validator: (value: any, cb: any) => {
          if (value && value.length > 30) {
            cb('不能超过 30位字符');
          } else {
            cb();
          }
        },
      },
    ],
    deliveryEmpName: [
      { required: true, message: '不能为空' },
      {
        validator: (value: any, cb: any) => {
          if (value && value.length > 30) {
            cb('不能超过 30位字符');
          } else {
            cb();
          }
        },
      },
    ],
  };

  async function handleOk(done: any) {
    const res = await formRef.value.validate();
    if (res) {
      done(false);
    } else {
      const data = await addPerson(form.value);
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
        booleanStore.toggleBool(15);
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
        booleanStore.toggleBool(15);
      }
      booleanStore.watchUpdate(28);
      done();
    }
  }
</script>

<template>
  <a-drawer
    :width="500"
    :height="340"
    :visible="showDrawer"
    placement="right"
    @after-visible-change="afterVisibleChange"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <template #title> 新增配送员 </template>
    <div>
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :style="{ width: '450px' }"
      >
        <a-form-item field="deliveryEmpCode" label="编号:">
          <a-input v-model="form.deliveryEmpCode" placeholder="配送人编号" />
        </a-form-item>
        <a-form-item field="deliveryEmpName" label="名字:">
          <a-input v-model="form.deliveryEmpName" placeholder="配送人名字" />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<style scoped>
  .add {
    background-color: #bacf65;
    color: #fff;
  }
  .clear {
    margin-left: 10px;
  }
</style>
